package com.zaizai.controller;
import com.zaizai.domain.AjaxResult;
import com.zaizai.utils.EmailApi;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.UUID;

/**
 * 邮箱Controller
 */
@Slf4j
@RestController
@RequestMapping("/email")
public class EmailController {
    @Resource
    private EmailApi emailApi;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送重置密码邮件
     *
     */
    @PostMapping("/resetPassword")
    public AjaxResult resetPassword(@RequestParam("email") String email) {
        if (redisTemplate.opsForValue().get("resetPasswordCaptcha:" + email) != null){
            return AjaxResult.error("请勿重复发送验证码,请稍等5分钟哈！");
        }
        //以当前时间戳生成一个六位的随机字符
        String captchaString = UUID.randomUUID().toString().substring(0, 6);
        // 将验证码存入redis中，设置过期时间为5分钟
        redisTemplate.opsForValue().set("resetPasswordCaptcha:" + email, captchaString, Duration.ofMinutes(5));
        log.info("发给{}的重置密码的验证码为：{}", email,captchaString);
        String captcha = "您的验证码为：" + captchaString + "，请在5分钟内完成验证。要尽快哦！";
        if (emailApi.sendGeneralEmail("崽崽给您提供的重置密码的验证码", captcha, email)) {
            return AjaxResult.success(captchaString);
        }
        return AjaxResult.error("邮箱发送失败");
    }

    /**
     * 发送登录或注册邮件
     */
    @PostMapping("/into")
    public AjaxResult into(@RequestParam("email") String email) {
        if (redisTemplate.opsForValue().get("captcha:" + email) != null){
            return AjaxResult.error("请勿重复发送验证码,请稍等5分钟哈！");
        }
        //以当前时间戳生成一个六位的随机字符
        String captchaString = UUID.randomUUID().toString().substring(0, 6);
        // 将验证码存入redis中，设置过期时间为5分钟
        redisTemplate.opsForValue().set("captcha:" + email, captchaString, Duration.ofMinutes(5));
        log.info("发给{}的验证码为：{}", email,captchaString);
        String captcha = "您的验证码为：" + captchaString + "，请在5分钟内完成验证。要尽快哦！";
        if (emailApi.sendGeneralEmail("崽崽给您提供的验证码", captcha, email)) {
            return AjaxResult.success(captchaString);
        }
        return AjaxResult.error("邮箱发送失败");
    }
}
